<template>
  <JVxeTable
    ref="tableRef"
    stripe
    toolbar
    keepSource
    rowNumber
    rowSelection
    asyncRemove
    dragSort
    :height="650"
    :sync-resize="activeKey"
    :checkboxConfig="{range: true}"
    :disabledRows="{ isPk: [true] }"
    :loading="loading"
    :disabled="disabled"
    :columns="columns"
    :dataSource="dataSource"
    @valueChange="handleValueChange"
    @removed="handleRemoved"
  >
  </JVxeTable>
</template>

<script lang="ts" setup>
  import {ref, onUnmounted, watch } from 'vue';
  import { JVxeColumn, JVxeTableInstance } from '/@/components/jeecg/JVxeTable/types'
  import { useMessage } from '/@/hooks/web/useMessage'
  import { batchDeleteGenTableColumn } from '../../codeGen.api'
  import { genTableColumns } from '../../codeGen.data'
  const { createMessage } = useMessage()

  const tableRef = ref<JVxeTableInstance>()
  const loading = ref(false)
  const disabled = ref(false)
  const isInit = ref(false)
  const dataSource = ref<Recordable[]>([])
  const columns = ref<JVxeColumn[]>(genTableColumns)
  const props = defineProps({
    // 子组件接收父组件传递过来的值
    rowId: String,
    activeKey: String,
    tableColumns: Array<Recordable>
  })

  const handleValueChange = (event) => {
    // console.log("handleValueChange, event: ", event)
    // const data = tableRef.value!.getTableData()
    // emit("update:tableColumns", data)
  }

  const getData = () => {
    const data = tableRef.value!.getTableData()
    return data
  }

  const validate = async (callback: Function) => {
    const values = tableRef.value!.getTableData()
    for(const item in values) {
      const errMap = await tableRef.value!.validateTable(values[item])
      if (errMap) {
        console.log('表单验证未通过：', { errMap });
        if (callback) {
          callback()
        }
        await tableRef.value!.validateTable()
        return false
      } 
    } 
    return true
  }

  watch(
    () => props.tableColumns,
    async  (val) => {
      try {
        if (val && !isInit.value) {
          dataSource.value = val
          isInit.value = true
        }
      } catch(err) {
        console.error(err)
      }
    },
    { deep: true, immediate: true }
  );
  onUnmounted(() => {
    console.log("onUnmounted GenTableColumn")
  })


  const handleRemoved = async (event) => {
    console.log("event: ", event)
    const hideLoading = createMessage.loading('删除中…', 0);
    try {
      let ids = []
      event.deleteRows.forEach(x => {
        console.log("x.id: ", x.id)
        if (!x.id.includes("row")) {
          ids.push(x.id)
        }
      })
      if (ids.length == 0) {
        return
      }
      console.log("delete ids: ", ids)
      await batchDeleteGenTableColumn(ids)
      createMessage.success('删除成功！');
    } catch(e) {
      createMessage.warn('删除失败！');
    } finally {
      await tableRef.value!.removeSelection();
      hideLoading();
    }
  }

  defineExpose({getData, validate})
</script>